import { extend } from 'umi-request';

const codeMaps: any = {
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};
const errorHandler = function (error: { response: Response }): Response {
  if (error.response) {
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx
    console.log(error.response.status);
    console.log(error.response.headers);
    console.log(codeMaps[error.response.status]);
  } else {
    // The request was made but no response was received or error occurs when setting up the request.
    console.log(error);
  }
  throw error; // If throw. The error will continue to be thrown.
};

const request = extend({
  errorHandler,
  prefix: '',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json;',
  },
});

request.interceptors.request.use((url, options) => {
  return {
    url: `${url}`,
    options: { ...options },
  };
});

request.interceptors.response.use(async (response: any) => {
  const data = await response.clone().json();
  return data;
});

export default request;
